﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using ScrumTable.Common;
using ScrumTable.Common.Collections;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Security;
using ScrumTable.DL.Data.Generic.Cache;
using ScrumTable.DL.Data.Schema.ScrumTableV1;
using ScrumTable.DL.Data.TFS.Bulk.Properties;
using ScrumTable.DL.Data.TFS.Bulk.Services.Utils;
using ScrumTable.DL.Data.TFS.Services.TeamFoundation;

using IterationBucket = ScrumTable.DL.Data.Generic.Cache.CacheElementListEntryBucket<ScrumTable.DL.Data.Generic.Cache.CacheIteration>;
using IterationSavePair = ScrumTable.DL.Data.Generic.Cache.CacheSavePair<ScrumTable.DL.Data.Generic.Cache.CacheElementListEntryBucket<ScrumTable.DL.Data.Generic.Cache.CacheIteration>>;

#endregion

namespace ScrumTable.DL.Data.TFS.Bulk.Services.IterationHandling
{
    /// <summary>
    /// This class is used to save all data below a given iteration.
    /// </summary>
    internal class TfsIterationSaver : IterationSaverBase
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new TfsIterationSaver with the associated schema config.
        /// </summary>
        /// <param name="schema">Specifies the schema configuration data.</param>
        internal TfsIterationSaver(IterationSchema schema)
            : base(schema)
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Stores the iterations to the back-end system.
        /// </summary>
        /// <param name="tfsContext">Specifies the tfs connection information.</param>
        /// <param name="changes">Specifies an instance with the data changes from the data layer.</param>
        internal override void SaveIterationData(TfsServerWrapper tfsContext, CacheDataChanges changes)
        {
            PreCondition.AssertNotNull(tfsContext, "tfsContext");
            PreCondition.AssertNotNull(changes, "changes");

            IDictionary<string, IterationSaveContext> iterationContexts = TryStoreIterations(tfsContext, changes);

            foreach (IterationBucket iterBucket in changes.ChangedIterations.Values)
            {
                if (iterationContexts.ContainsKey(iterBucket.Element.UniqueId)
                    && changes.IterationsToSync[iterBucket.Element.UniqueId].Errors.IsEmpty())
                {
                    changes.IterationsToSync[iterBucket.Element.UniqueId].State = CacheSavePairState.Saved;
                }
            }
        }

        private IDictionary<string, IterationSaveContext> TryStoreIterations(TfsServerWrapper tfsContext, CacheDataChanges changes)
        {
            IDictionary<string, IterationSaveContext> workItemsToStore = TryStoreIterationValues(tfsContext, changes);
            ValidateTfsWorkItemValues(workItemsToStore);
            TryStoreIterationWorkItems(tfsContext.WorkItems, workItemsToStore);
            ReportErrorsToSavePairs(changes, workItemsToStore);
            return workItemsToStore;
        }

        private void TryStoreIterationWorkItems(WorkItemStore store, IDictionary<string, IterationSaveContext> storedWorkItems)
        {
            IDictionary<int, Pair<string, IterationSaveContext>> wiIndex = storedWorkItems.Convert(
                wiPair =>
                    {
                        return new KeyValuePair<int, Pair<string, IterationSaveContext>>(
                            wiPair.Value.WorkItem.Id,
                            new Pair<string, IterationSaveContext>(wiPair.Key, wiPair.Value));
                    });

            store.TrySave(
                from iterCtx in storedWorkItems.Values
                    where iterCtx.Errors.IsEmpty()
                    select iterCtx.WorkItem,
                (exc, wi, fields) => HandleSaveError(exc, fields, wiIndex[wi.Id].Right));
        }

        private IDictionary<string, IterationSaveContext> TryStoreIterationValues(TfsServerWrapper tfsContext, CacheDataChanges changes)
        {
            try
            {
                return StoreIterationValues(tfsContext, changes);
            }
            catch (Exception e)
            {
                Logger<DataSaveProcess>.Error(Resources.ExcDataSaveProcIterWiRetrieveFailed, e);
                return new Dictionary<string, IterationSaveContext>(0);
            }
        }

        private IDictionary<string, IterationSaveContext> StoreIterationValues(TfsServerWrapper tfsContext, CacheDataChanges changes)
        {
            IDictionary<int, WorkItem> sprintWorkItems = GetSprints(tfsContext, changes);
            IDictionary<string, IterationSaveContext> toStoreBack = new Dictionary<string, IterationSaveContext>(sprintWorkItems.Count);

            foreach (var changedIteration in changes.ChangedIterations.Values)
            {
                if (HasWorkItemIdKeyAttribute(changedIteration.Element))
                {
                    int workItemId = GetWorkItemIdKeyAttribute(changedIteration.Element);

                    if (sprintWorkItems.ContainsKey(workItemId))
                    {
                        WorkItem sprint = sprintWorkItems[workItemId];
                        sprint.TrySetValue(Schema.StartTime, changedIteration.Element.StartDate);
                        sprint.TrySetValue(Schema.EndTime, changedIteration.Element.EndDate);
                        toStoreBack[changedIteration.Element.UniqueId] = new IterationSaveContext(sprint, changedIteration);
                    }
                }
            }
            return toStoreBack;
        }

        private int GetWorkItemIdKeyAttribute(CacheElementBase cacheElement)
        {
            return (int)cacheElement.Attributes[TfsIterationLoader.IterationWorkItemIdKey];
        }

        private bool HasWorkItemIdKeyAttribute(CacheElementBase cacheElement)
        {
            return (cacheElement.Attributes.ContainsKey(TfsIterationLoader.IterationWorkItemIdKey)
                    && (cacheElement.Attributes[TfsIterationLoader.IterationWorkItemIdKey] is int));
        }

        private IDictionary<int, WorkItem> GetSprints(TfsServerWrapper tfsContext, CacheDataChanges changes)
        {
            string query = string.Format(
                Resources.QuerySprintsById,
                Schema.SchemaMappedName,
                "{0}");

            WiqlQueryBuilder andQuery = new WiqlQueryBuilder();
            andQuery.AppendIdOrConditions(
                from iteration in changes.ChangedIterations.Values
                where HasWorkItemIdKeyAttribute(iteration.Element)
                select GetWorkItemIdKeyAttribute(iteration.Element) );

            WiqlQueryBuilder workItemQuery = new WiqlQueryBuilder(query, andQuery.ToString());

            IDictionary parameters = new Hashtable
                                         {
                                             {"project", changes.Project.Name}
                                         };

            return tfsContext.WorkItems.QueryWorkItemsAndIndex(workItemQuery, parameters);
        }


        #region Validation & Error Handling Procedures

        /// <summary>
        /// Simulate whole update in order to provide reliable error handling.
        /// </summary>
        private void ValidateTfsWorkItemValues(IDictionary<string, IterationSaveContext> localWorkItemStore)
        {
            // validate work items. this will prevent invalid work items to be sent back to
            // the server and provide additional error information
            foreach (var saveCandidate in localWorkItemStore.Values.ToArray())
            {
                // check if values can be stored onto tfs
                ValidateTfsWorkItem(saveCandidate);
            }
        }

        private void ValidateTfsWorkItem(IterationSaveContext toValidate)
        {
            IList<Field> invalidFields = toValidate.WorkItem.Validate().Convert(def => (Field)def);

            if (invalidFields.Count > 0)
            {
                HandleSaveError(null, invalidFields, toValidate);
            }
        }

        private void HandleSaveError(Exception error, ICollection<Field> invalidFields, IterationSaveContext saveContext)
        {
            // dump error trace
            saveContext.SaveTrace.DumpSaveErrorData(invalidFields);

            // make sure errors are stored into the WorkItemSaveContext in order to report them to the layers above
            saveContext.Errors.Add(
                invalidFields,
                field => new CacheSaveError(
                    error,
                    field.Name,
                    field.ReferenceName,
                    field.OriginalValue,
                    field.Value,
                    ErrorReasonEnumConverter.Convert(field.Status)));
        }

        private void ReportErrorsToSavePairs(CacheDataChanges changes, IDictionary<string, IterationSaveContext> loadedSaveContexts)
        {
            if (loadedSaveContexts != null)
            {
                foreach (var saveContextPair in loadedSaveContexts)
                {
                    // do not publish contexts which don't contain errors
                    if (saveContextPair.Value.Errors.IsEmpty()) { continue; }

                    // the errors can only be published if a curresponding
                    // Sync element is available
                    if (!changes.IterationsToSync.ContainsKey(saveContextPair.Value.CacheBucket.Element.UniqueId)) { continue; }

                    // the element couldn't be saved back to the back end system.
                    // let's report the error on the layers above
                    changes.IterationsToSync[saveContextPair.Value.CacheBucket.Element.UniqueId].Errors.Add(saveContextPair.Value.Errors);
                }
            }
        }

        #endregion


        #endregion


        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion



        //--------------------------------------------------------------------
        // Nested Classes
        //--------------------------------------------------------------------

        private class IterationSaveContext
        {
            #region Properties
            //--------------------------------------------------------------------
            // Properties
            //--------------------------------------------------------------------

            internal WorkItem WorkItem { get; private set; }
            internal IterationBucket CacheBucket { get; private set; }
            internal SaveTraceErrorProvider SaveTrace { get; private set; }
            internal IList<CacheSaveError> Errors { get; private set; }

            #endregion

            #region Constructors / Destructor
            //--------------------------------------------------------------------
            // Constructors / Destructor
            //--------------------------------------------------------------------

            internal IterationSaveContext(
                WorkItem workItem,
                IterationBucket bucket)
            {
                PreCondition.AssertNotNull(workItem, "workItem");
                PreCondition.AssertNotNull(bucket, "bucket");

                WorkItem = workItem;
                CacheBucket = bucket;
                Errors = new List<CacheSaveError>();
                SaveTrace = new SaveTraceErrorProvider(workItem, bucket.Element);
            }

            #endregion
        }
    }
}